package sample.jogl;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
  * This applet implements Runnable and uses a thread
  * to create a simple dropped ball demonstration.
 **/
public class Drop2DApplet extends JApplet
                        implements Runnable, ActionListener{
  // Will use thread reference as a flag
  Thread fThread;
  Drop2DPanel fDropPanel;
  JButton fDropButton;

  /** Build the interface. **/
  public void init () {
    Container content_pane = getContentPane ();
    content_pane.setLayout (new BorderLayout ());

    // Create an instance of DropPanel
    fDropPanel = new Drop2DPanel ();
    // Add the DropPanel to the content pane.
    content_pane.add ("Center",fDropPanel);

    // Create a button and add it
    fDropButton = new JButton ("Drop");
    fDropButton.addActionListener (this);
    content_pane.add ("South",fDropButton);

  } // init

  /** Start when browser is loaded or button pushed. **/
  public void start () {
    // If the thread reference not null then a
    // thread is already running. Otherwise, create
    // a thread and start it.
    if (fThread == null){
        fThread = new Thread (this);
        fThread.start ();
    }
  } // start

  /** Applet's stop method used to stop thread.**/
  public void stop () {
     // Setting thread to null will cause loop in
     // run () to finish and kill the thread.
     fThread = null;
  }

  /** Button command. **/
  public void actionPerformed (ActionEvent ae){
    if (fDropPanel.isDone ()) start ();
  }

  /** The thread loops to draw each frame of drop.**/
  public void run () {
    // Disable button during drop
    fDropButton.setEnabled (false);

    // Initialize the ball for the drop.
    fDropPanel.reset ();

    // Loop through animation frames
    while ( fThread != null){
       // Sleep 25msecs between frames
      try{ Thread.sleep (25);
      } catch  (InterruptedException e) { }
      // Repaint drop panel for each new frame
      fDropPanel.repaint ();
      if (fDropPanel.isDone ()) fThread = null;
    }
    // Enable button for another drop
    fDropButton.setEnabled (true);
  } // run
} // class DropApplets